package com.tianshuo.beta.sso.service.impl;

import com.tianshuo.beta.sso.aop.exception.LoginException;
import com.tianshuo.beta.sso.dao.UserMapper;
import com.tianshuo.beta.sso.model.User;
import com.tianshuo.beta.sso.service.AuthenticationService;
import com.tianshuo.beta.sso.ticket.LoginTicket;
import com.tianshuo.beta.sso.ticket.ServiceTicket;
import com.tianshuo.beta.sso.ticket.TicketException;
import com.tianshuo.beta.sso.ticket.registry.TicketRegistry;
import com.tianshuo.beta.sso.util.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import java.util.concurrent.ExecutorService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * 验证服务类
 *
 * @author tianshuo
 */
@Slf4j
@Service
public class AuthenticationServiceImpl implements AuthenticationService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private TicketRegistry ticketRegistry;

    // 注入异步线程池
    @Autowired
    @Qualifier("httpAsyncExecutor")
    private ExecutorService httpAsyncExecutor;

    /**
     * 登录接口
     *
     * @param user
     * @return
     */
    @Override
    public User login(User user) {
        if(StringUtils.isEmpty(user.getLoginName())||StringUtils.isEmpty(user.getPassword())){
            return null;
        }
        // 使用新的Mapper方法替代UserExample
        User userInfo = userMapper.selectByLoginNameAndPassword(user.getLoginName(), user.getPassword());
        if (userInfo != null) {
            return userInfo;
        }
        throw new LoginException("账号或密码错误");
    }

    /**
     * 登出接口
     *
     * @return
     */
    @Override
    public boolean logout(String ticketId) {
        if (log.isDebugEnabled()) {
            log.debug("logout ticket [{}] ..", ticketId);
        }

        // 获取登录票据
        LoginTicket loginTicket = (LoginTicket) ticketRegistry.getTicket(ticketId);
        if (loginTicket != null) {
            List<ServiceTicket> serviceTicketList = loginTicket.getServiceTicketList();
            // 异步处理所有服务票据的登出请求
            for (ServiceTicket serviceTicket : serviceTicketList) {
                // 提交异步任务
                httpAsyncExecutor.submit(() -> {
                    try {
                        HttpUtil client = new HttpUtil(serviceTicket.getService());
                        client.setRequest("logout=logout&ticket=" + serviceTicket.getId());
                        client.call();
                        log.debug("{} 登出成功", serviceTicket.getService());
                    } catch (Exception e) {
                        log.error("{} 登出失败: {}", serviceTicket.getService(), e.getMessage(), e);
                    }
                });
            }
        }

        // 删除登录票据(立即执行，不等待异步任务完成)
        ticketRegistry.deleteTicket(ticketId);
        return true;
    }

    /**
     * 票据校验接口
     * 1、服务票据一次失效
     *
     * @param serviceTicketId
     * @return
     */
    @Override
    public User validate(String serviceTicketId) {
        if (log.isDebugEnabled()) {
            log.debug("validate ticket [{}] ..", serviceTicketId);
        }
        ServiceTicket serviceTicket = (ServiceTicket) ticketRegistry.getTicket(serviceTicketId);
        if (serviceTicket != null) {
            LoginTicket loginTicket = (LoginTicket) ticketRegistry.getTicket(serviceTicket.getLoginTicket().getId());
            ticketRegistry.deleteTicket(serviceTicketId);
            return loginTicket.getUserInfo();
        }

        throw new TicketException("票据失效");
    }

    /**
     * 校验登录票是否存在
     *
     * @param loginTicketId
     * @return
     */
    @Override
    public boolean tgtValidate(String loginTicketId) {
        if (log.isDebugEnabled()) {
            log.debug("validate loginTicketId [{}] ..", loginTicketId);
        }
        return ticketRegistry.getTicket(loginTicketId) != null;
    }


}
